package com.ncucoder.demo.web;

import com.ncucoder.demo.model.Customer;
import com.ncucoder.demo.service.CustomerService;
import com.ncucoder.demo.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 *
 * @author <a href="https://edit.ncucoder.com">hsowan</a>
 * @since 2018-12-23 03:28
 */
@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    /**
     * List customer by pagination
     *
     * @param page current page index
     * @param size how many to show
     * @return com.ncucoder.demo.vo.Response
     */
    @GetMapping
    public Response listCustomers(@RequestParam int page, @RequestParam int size){
        List<Customer> list = customerService.listCustomers(page, size);
        if (list != null){
            for (Customer customer: list){
                System.out.println(customer.toString());
            }
            return new Response(true, "List customers successfully!", list);
        }
        return new Response(false, "List customers unsuccessfully!", null);
    }

    @GetMapping("/{id}")
    public Response getCustomerById(@PathVariable Long id){
        Customer customer = customerService.getCustomerById(id);
        if (customer != null){
            return new Response(true, "Get customer successfully!", customer);
        }
        return new Response(false, "Get customer unsuccessfully!", null);
    }

    @PostMapping
    public Response saveOrUpdateCustomer(@RequestBody Customer customer){
        if (customer.getId() != null){
            int result = customerService.updateCustomer(customer);
            if (result == 0) {
                return new Response(false, "Update customer unsuccessfully!", null);
            }
            return new Response(true, "Update customer successfully!", null);
        } else {
            int result = customerService.saveCustomer(customer);
            if (result == 0){
                return new Response(false, "Add customer unsuccessfully!", null);
            }
            return new Response(true, "Add customer successfully!", null);

        }
    }

    @DeleteMapping("/{id}")
    public Response deleteCustomerById(@PathVariable Long id){
        int result = customerService.deleteCustomerById(id);
        if (result == 0){
            return new Response(false, "Delete customer unsuccessfully!", null);
        }
        return new Response(true, "Delete customer successfully!", null);
    }

    @GetMapping("/count")
    public Response count(){
        int count = customerService.count();
        if (count >= 0){
            return new Response(true, "Get count successfully!", count);
        }
        return new Response(true, "Get count unsuccessfully!", null);
    }
}
